package com.jk.goodsclassify.classify.utils;

import com.jk.goodsclassify.classify.entry.Library;

import java.util.*;

public class Screening {

    private Library library;
    private final int UPPER_LIMIT = 1000;
    private final int LOWER_LIMIT = 1;

    public Screening(Library library){
        this.library = library;
    }

    public Library FilterLowerAndUpper(){
        Iterator iterator = library.iterator();
        Map.Entry<String,Integer> entry;
        while (iterator.hasNext()){
            entry = (Map.Entry<String, Integer>) iterator.next();
            int amount = entry.getValue();
            if(amount<=LOWER_LIMIT || amount>=UPPER_LIMIT){
                iterator.remove();
            }
        }
        return library;
    }

    public Map<String,Integer> getTopN(int n){
        Map<String,Integer> topN = new LinkedHashMap<String, Integer>();
        int max = 0;
        String maxWord = null;
        for(int i=0;i<n;i++){
            for (Map.Entry<String,Integer> entry:library.getData().entrySet()){
                int count = entry.getValue();
                if(count>max){
                    max = count;
                    maxWord = entry.getKey();
                }
            }
            topN.put(maxWord,max);
            max = 0;
            //暂时移走，方便排序
            library.remove(maxWord);
            maxWord = null;
        }
        //还回去
        returnInfo(topN);
        return topN;
    }

    private void returnInfo(Map<String,Integer> map){
        Iterator iterator = map.entrySet().iterator();
        while(iterator.hasNext()){
            Map.Entry<String,Integer> entry = (Map.Entry) iterator.next();
            library.put(entry.getKey(),entry.getValue());
        }
    }

    public Library filterLower(){
        Iterator iterator = library.iterator();
        Map.Entry<String,Integer> entry;
        while (iterator.hasNext()){
            entry = (Map.Entry<String, Integer>) iterator.next();
            if(entry.getValue()<2){
                iterator.remove();
            }
        }
        return library;
    }
}
